<template>
  <div style="width: 100%" class="cc-datetime">
    <span v-if="props.showText">{{currValue || ''}}</span>
    <el-date-picker
      v-else
      v-model="currValue"
      type="datetime"
      style="width: 100%"
      :format="format"
      :value-format="valueFormat"
      @change="handleChange"
      @blur="handleBlur"
    />
  </div>
</template>

<script setup>
import { inject, ref, watch } from 'vue';
import date from "@/utils/date";

const emit = defineEmits(['change', 'blur']);
const props = defineProps({
  prop: {
    type: String,
    default: ''
  },
  options: Object,
  format: {
    type: String,
    default: 'YYYY-MM-DD HH:mm:ss'
  },
  valueFormat: {
    type: String,
    default: 'YYYY-MM-DD HH:mm:ss'
  },
  showText: Boolean,
});

const formData = inject('formData');
const currValue = ref('');

const handleChange = () => {
  emit('change');
};

const handleBlur = () => {
  emit('blur');
};

watch(() => formData.value[props.prop], (val) => {
  if (val) {
    currValue.value = date.formatLongDate(val);
  } else {
    currValue.value = '';
  }
}, { immediate: true });

watch(() => currValue.value, (val) => {
  if (val) {
    formData.value[props.prop] = new Date(val.replace(/-/g, '/')).getTime();
  } else {
    formData.value[props.prop] = '';
  }
});
</script>